# -*- coding: utf-8 -*-
# @Time    : 2024/11/7 下午1:56
# @Author  : xiaowanzi
# @File    : log.py
import os
import time
import colorlog
import socket
from base.project_path import get_project_path
from base.uploadLogFileHandler import UploadLogFileHandler

# import inspect
# frame = inspect.currentframe().f_back
# print(f"调用者 {frame.f_code.co_filename} 调用行号 {frame.f_lineno}")

log_path = get_project_path() + "\\logs"
if not os.path.exists(log_path):
    os.mkdir(log_path)  # 如果不存在这个logs文件夹，就自动创建一个
log_name = os.path.join(log_path, '%s.Logs' % time.strftime('%Y-%m-%d'))  # 文件的命名
log_colors_config = {
    'DEBUG': 'light_cyan',
    'INFO': 'light_green',
    'WARNING': 'light_yellow',
    'ERROR': 'light_red',
    'CRITICAL': 'light_red',
}


class MyLogger(object):

    def __init__(self, name='root'):
        self.logger = None
        self.name = name
        self.my_logger()
        self.LOG_END_FORMAT = r"f'--[{case_id},{run_id}]'"

    def my_logger(self):
        import logging
        # 创建一个logger
        self.logger = logging.getLogger(self.name)
        self.logger.setLevel(logging.DEBUG)  # 设置日志级别

        # 创建一个handler，用于写入日志文件
        formatter = colorlog.ColoredFormatter(
            '%(log_color)s[%(asctime)s]-[%(name)s]-'
            '[%(filename)s]-[%(funcName)s]-[%(lineno)d]-'
            '[%(threadName)s]-[%(thread)d]-[%(levelname)s]:'
            ' %(message)s',
            log_colors=log_colors_config)
        fh = UploadLogFileHandler(filename=log_name, mode='a', maxBytes=1024 * 1024 * 5, backupCount=5,
                             encoding='utf-8')  # 使用RotatingFileHandler类，滚动备份日志
        fh.setLevel(logging.DEBUG)
        # 定义handler的输出格式
        fh.setFormatter(formatter)
        # 给logger添加handler
        self.logger.addHandler(fh)

        # 创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        fh.setLevel(logging.DEBUG)
        ch.setFormatter(formatter)
        self.logger.addHandler(ch)

    def info(self, msg, case_id=None, run_id=None):
        self.logger.info(str(msg) + f"{eval(self.LOG_END_FORMAT)}", stacklevel=2)

    def error(self, msg, case_id=None, run_id=None):
        self.logger.error(str(msg) + f"{eval(self.LOG_END_FORMAT)}", stacklevel=2)

    def critical(self, msg, case_id=None, run_id=None):
        self.logger.critical(str(msg) + f"{eval(self.LOG_END_FORMAT)}", stacklevel=2)

    def warning(self, msg, case_id=None, run_id=None):
        self.logger.warning(str(msg) + f"{eval(self.LOG_END_FORMAT)}", stacklevel=2)

    def debug(self, msg, case_id=None, run_id=None):
        self.logger.debug(str(msg) + f"{eval(self.LOG_END_FORMAT)}", stacklevel=2)


logger = MyLogger(socket.gethostname())